package ro.fortech.workshop_demo.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.widget.ProgressBar;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * User: florinv
 * Date: 4/16/13
 * Time: 10:35 AM
 */
public class Utils {
    /**
     * Progress dialog
     */
    private static Dialog progressDialog;
    /**
     * Holds reference to the application context
     */
    private static Context applicationContext;


    public static Context getApplicationContext() {
        return applicationContext;
    }

    public static void setApplicationContext(Context applicationContext) {
        Utils.applicationContext = applicationContext;
    }

    /**
     * Method that navigates to another activity
     *
     * @param activity      : current activity
     * @param activityClass : class of the destination activity
     * @param finish        : if true current activity will be finished
     * @param bundle        : extended data that will be added to the intent that is used for starting the activity
     * @param animationIn   : the animation for activity entering the screen
     * @param animationOut  : the animation for activity leaving the screen
     */
    public static void navigate(Activity activity, Class activityClass, boolean finish, Bundle bundle,
                                int animationIn, int animationOut) {
        Intent intent = new Intent();
        intent.setClass(activity, activityClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        if (finish) {
            activity.startActivity(intent);
            activity.setResult(Activity.RESULT_OK);
            activity.finish();
        } else {
            // Launching a child activity. We are interested in it's result so
            // we can end this activity also if needed when the child activity ends
            activity.startActivityForResult(intent, Activity.RESULT_FIRST_USER);
        }
        activity.overridePendingTransition(animationIn, animationOut);
    }

    /**
     * Will show the progress dialog on a given activity
     */
    public static void showProgressDialog(Activity activity) {
        if ((progressDialog == null) || (!progressDialog.isShowing())) {
            progressDialog = new Dialog(activity);
            progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            progressDialog.setContentView(new ProgressBar(activity));
            progressDialog.getWindow().getCurrentFocus();
            progressDialog.setCancelable(false);
            progressDialog.setOwnerActivity(activity);
            progressDialog.show();
        } else {
            progressDialog.setOwnerActivity(activity);
        }
    }

    /**
     * Will hide the progress dialog on a given activity
     *
     * @param activity
     */
    public static void hideProgressDialog(Activity activity) {
        if (progressDialog != null && progressDialog.isShowing() && (activity == progressDialog.getOwnerActivity())) {
            try {
                progressDialog.dismiss();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Method used for constructing an URL that allows receiving the response in JSON format
     */
    public static String getValidUrl(String url) {
        return url + ".json";
    }

    /**
     * Downloads the image on a p2g_background thread: sends the image (as Bitmap)
     * to the handler in the Message obj parameter if it was successful. If
     * image retrieval was successful the what parameter of the Message will be
     * HAS_IMAGE If not it will be NO_IMAGE and no image will be attached in the
     * obj parameter of the message
     *
     * @param imageURL the url form where the image will be retrieved
     */
    public static Bitmap downloadImage(String imageURL) {
        URL fileUrl;
        try {
            fileUrl = new URL(imageURL);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
        try {
            HttpURLConnection conn;
            conn = (HttpURLConnection) fileUrl.openConnection();
            if (conn != null) {
                conn.setDoInput(true);
            }
            if (conn != null) {
                conn.connect();
            }
            InputStream is = null;
            if (conn != null) {
                is = conn.getInputStream();
            }
            return BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (OutOfMemoryError error) {
            return null;
        }
    }

    /**
     * Method used for escaping inverted commas
     *
     * @param task : the background task that needs to be executed
     * @param link : the image link
     */

    public static void executeDownLoadImageTask(AsyncTask<String, Void, Bitmap> task, String link) {
        if (Build.VERSION.SDK_INT >= 11) {
            // execute in parallel by specifying the executor
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, link);
        } else {
            // parallel execution by default
            task.execute(link);
        }
    }
}
